package com.atguigu.lease.web.app.intenrceptors;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.BusException;
import com.atguigu.lease.common.jwtutil.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationAdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String accessToken = request.getHeader("access-token");
        System.out.println(accessToken);
        if (accessToken == null){
            throw new BusException(ResultCodeEnum.APP_LOGIN_AUTH);
        }else{
            Claims claims = JwtUtil.parseToken(accessToken);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            //解析出来的数据，后期在接口当中使用，我们应该把这个方法放到线程都可找到的地方，最好是放到ThreadLocal中

            LoginUser loginUser= new LoginUser();
            loginUser.setUserId(userId);
            loginUser.setUsername(username);

            LoginUserContext.setLoginUser(loginUser);

            return true;
        }


    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //善后处理
        LoginUserContext.removeLoginUser();

    }
}
